package com.justalk.learnofaidl;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.justalk.serverservice.Book;
import com.justalk.serverservice.BookController;
import com.justalk.serverservice.IOnNewBookArrivedListener;

import java.util.List;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    private static final int MESSAGE_NEW_BOOK_ARRIVE = 1;
    private List<Book> bookList;
    private BookController bookController;
    private boolean hasConnected;

    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MESSAGE_NEW_BOOK_ARRIVE:
                    String updateDescriptionText = (String) msg.obj;
                    Log.e(TAG, "onNewBookArrived" + msg.obj);
                    tvContentDetail.setText(
                            String.format(Locale.getDefault(), "%s\n%s"
                                    , tvContentDetail.getText()
                                    , updateDescriptionText));
            }
        }
    };


    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bookController = BookController.Stub.asInterface(service);
            try {
                service.linkToDeath(new IBinder.DeathRecipient() {
                    @Override
                    public void binderDied() {
                        Log.d(TAG,"binder监听到服务断开连接了");
                    }
                },0);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            hasConnected = true;
            Log.e(TAG, "服务绑定成功");
            try {
                bookController.registerListener(mIOnNewBookArrivedListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            hasConnected = false;
            Log.e(TAG, "服务绑定失败");
        }
    };

    private IOnNewBookArrivedListener mIOnNewBookArrivedListener = new IOnNewBookArrivedListener.Stub() {
        @Override
        public void onNewBookArrived(Book newBook) throws RemoteException {
            mHandler.obtainMessage(MESSAGE_NEW_BOOK_ARRIVE,newBook.getName()).sendToTarget();
        }
    };
    private TextView tvContentDetail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_getBookList).setOnClickListener(this);
        findViewById(R.id.btn_addBook_inOut).setOnClickListener(this);
        tvContentDetail = findViewById(R.id.tv_update_content);
        tvContentDetail.setMovementMethod(ScrollingMovementMethod.getInstance());
        tvContentDetail.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                v.getParent().requestDisallowInterceptTouchEvent(true);
            }
            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                v.getParent().requestDisallowInterceptTouchEvent(true);
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                v.getParent().requestDisallowInterceptTouchEvent(false);
            }
            return false;
        });
        bindService();

    }

    private void bindService() {
        Log.e(TAG, "now bindService" + Thread.currentThread().getName());
        ComponentName componentName = new ComponentName("com.justalk.serverservice", "com.justalk.serverservice.service.AIDLService");
        Intent intent = new Intent();
        intent.setComponent(componentName);
        bindService(intent, serviceConnection, BIND_AUTO_CREATE);
        Log.e(TAG, "over bindService");

    }

    private void log() {
        for (Book book : bookList) {
            Log.e(TAG, book.toString());
            mHandler.obtainMessage(MESSAGE_NEW_BOOK_ARRIVE,book.toString()).sendToTarget();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_getBookList:
                if (hasConnected) {
                    try {
                        bookList = bookController.getBookList();
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    log();
                }
                break;
            case R.id.btn_addBook_inOut:
                if (hasConnected) {
                    Book book = new Book("这是一本新书 InOut");
                    try {
                        bookController.addBook(book);
                        Log.e(TAG, "向服务器以InOut方式添加了一本新书");
                        Log.e(TAG, "新书名：" + book.getName());
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (hasConnected) {
            if (bookController!= null && bookController.asBinder().isBinderAlive()) {
                try {
                    bookController.unregisterListener(mIOnNewBookArrivedListener);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
            unbindService(serviceConnection);
        }
    }
}
